package com.movies.service.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.User;
import com.movies.service.service.UserService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;


@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    private UserService userService;

//    用户登录（支持用户名/邮箱/手机号 + 密码）
    @PostMapping("/login")
    public Result login(@RequestBody LoginReq req) {
        if (req.getAccount() == null || req.getPassword() == null) {
            return Result.error(Constants.CODE_500, "请输入账号与密码");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUname, req.getAccount())
                .or().eq(User::getEmail, req.getAccount())
                .or().eq(User::getPhone, req.getAccount());
        User user = userService.getOne(wrapper);
        if (user == null) {
            return Result.error(Constants.CODE_500, "账号或密码错误，请重试");
        }
        if (user.getStatus() != null && user.getStatus() == 0) {
            return Result.error(Constants.CODE_400, "账号已禁用");
        }
        String pwdMd5 = SecureUtil.md5(req.getPassword());
        if (!pwdMd5.equalsIgnoreCase(user.getPassword())) {
            return Result.error(Constants.CODE_500, "账号或密码错误，请重试");
        }
        StpUtil.login(user.getId());
        StpUtil.getSession().set("user", user);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return Result.success("登录成功", tokenInfo);
    }

//    用户注册
    @PostMapping("/register")
    public Result register(@RequestBody RegisterReq req) {
        if (req.getUname() == null || req.getPassword() == null) {
            return Result.error(Constants.CODE_500, "请输入用户名与密码");
        }
        // 唯一性校验：用户名/邮箱
        boolean existsName = userService.count(new LambdaQueryWrapper<User>().eq(User::getUname, req.getUname())) > 0;
        if (existsName) {
            return Result.error(Constants.CODE_300, "用户名已存在");
        }
        if (req.getEmail() != null) {
            boolean existsEmail = userService.count(new LambdaQueryWrapper<User>().eq(User::getEmail, req.getEmail())) > 0;
            if (existsEmail) {
                return Result.error(Constants.CODE_300, "邮箱已存在");
            }
        }
        User user = new User();
        user.setUname(req.getUname());
        user.setPassword(SecureUtil.md5(req.getPassword()));
        user.setPhone(req.getPhone());
        user.setEmail(req.getEmail());
        user.setStatus(1);
        // 角色与时间由DB默认或前端选择处理
        boolean ok = userService.save(user);
        return ok ? Result.success("注册成功") : Result.error(Constants.CODE_600, "注册失败");
    }

//    查看个人信息
    @GetMapping("/profile")
    @SaCheckLogin
    public Result profile() {
        User user = (User) StpUtil.getSession().get("user");
        if (user == null) {
            Object loginId = StpUtil.getLoginIdDefaultNull();
            if (loginId != null) {
                user = userService.getById(Long.valueOf(loginId.toString()));
            }
        }
        return Result.success(user);
    }

//    更新个人信息（仅允许修改电话、邮箱、头像、简介）
    @PutMapping("/profile")
    @SaCheckLogin
    public Result updateProfile(@RequestBody UpdateProfileReq req) {
        Long loginId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(loginId);
        if (user == null) {
            return Result.error(Constants.CODE_600, "用户不存在");
        }
        user.setPhone(req.getPhone());
        user.setEmail(req.getEmail());
        user.setAvatarUrl(req.getAvatarUrl());
        user.setBio(req.getBio());
        boolean ok = userService.updateById(user);
        if (ok) {
            StpUtil.getSession().set("user", user);
        }
        return ok ? Result.success("更新成功") : Result.error(Constants.CODE_600, "更新失败");
    }

//    注销当前登录
    @PostMapping("/logout")
    @SaCheckLogin
    public Result logout() {
        StpUtil.logout();
        return Result.success("已注销");
    }

//    充值余额
    @PostMapping("/recharge")
    @SaCheckLogin
    public Result recharge(@RequestBody RechargeReq req) {
        if (req.getAmount() == null || req.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error(Constants.CODE_500, "充值金额需大于 0");
        }
        Long loginId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(loginId);
        if (user == null) {
            return Result.error(Constants.CODE_600, "用户不存在");
        }
        BigDecimal current = user.getBalance() == null ? BigDecimal.ZERO : user.getBalance();
        user.setBalance(current.add(req.getAmount()));
        boolean ok = userService.updateById(user);
        if (ok) { StpUtil.getSession().set("user", user); }
        return ok ? Result.success("充值成功", user.getBalance()) : Result.error(Constants.CODE_600, "充值失败");
    }

//    重置密码为默认 123456
    @PostMapping("/reset-password")
    @SaCheckLogin
    public Result resetPassword() {
        Long loginId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(loginId);
        if (user == null) {
            return Result.error(Constants.CODE_600, "用户不存在");
        }
        user.setPassword(SecureUtil.md5("123456"));
        boolean ok = userService.updateById(user);
        return ok ? Result.success("重置成功") : Result.error(Constants.CODE_600, "重置失败");
    }

//     登录请求体
    @Data
    public static class LoginReq {
        private String account; // 用户名/邮箱/手机号之一
        private String password;
    }

//     注册请求体
    @Data
    public static class RegisterReq {
        private String uname;
        private String password;
        private String phone;
        private String email;
    }

//    更新个人信息请求体
    @Data
    public static class UpdateProfileReq {
        private String phone;
        private String email;
        private String avatarUrl;
        private String bio;
    }

//     充值请求体
    @Data
    public static class RechargeReq {
        private BigDecimal amount;
    }
}
